#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<vector>
#include<unordered_map>

using namespace std;

int get(vector<int>& nums, int k)
{
    unordered_map<int, int> m;
    int n = nums.size();
    int l = 0, r = 0;
    int res = 0;
    while (r < n)
    {
        m[nums[r++]]++;
        while (m.size() > k)
        {
            m[nums[l]]--;
            if (m[nums[l]] == 0) m.erase(nums[l]);
            l++;
        }
        res += r - l;
    }
    return res;
}
int subarraysWithKDistinct(vector<int>& nums, int k) {
    return get(nums, k) - get(nums, k - 1);
}